package com.zhou.framework.job;

import com.zhou.framework.util.SettingUtil;
import com.zhou.util.DateUtil;
import com.zhou.util.FileUtil;
import com.zhou.util.ObjectUtil;
import com.zhou.framework.quartz.job.JobTask;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;

import java.io.File;
import java.util.Date;

/**
 * @author lang.zhou
 * @since 2023/3/8 17:24
 */
@Slf4j
public class UploaderFileCleanJob extends JobTask {
    @Override
    public void run(JobExecutionContext context) {
        Date date = context == null ? new Date() : context.getFireTime();

        File baseDir = new File(SettingUtil.getTempDir() + "/uploader");
        //临时文件保留天数
        int cleanDay = SettingUtil.getInteger("uploader", "tempFileCleanDay", 1);
        log.info("清理系统上传的临时文件，保留天数【{}】",cleanDay);

        String lastDay = DateUtil.getLastDay(date, cleanDay);
        this.doClean(baseDir, lastDay);

    }

    private void doClean(File baseDir, String lastDay){
        File[] files = baseDir.listFiles();
        if(ObjectUtil.isNotEmpty(files)){
            for (File file : files) {
                if(file.getName().compareTo(lastDay) < 0){
                    FileUtil.safeDelete(file);
                }
            }
        }
    }
}
